// Copyright 2019 chnykn@gmail.com All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package toolfunc

import (
	"encoding/json"
	"fmt"
	"github.com/imroc/req"
	"io/ioutil"
	"net/http"
	"strings"
)

// NewServiceClient ***
func NewServiceClient() *ServiceClient {
	o := &ServiceClient{
		request: req.New(),
	}
	//o.request.Header.Set("Content-Type", "application/json")
	o.request.SetTimeout(0)

	return o
}

//----------------------------------------------------------------------

// ----------------------------------------------------------------------
func HttpPost(url, token string, parMap interface{}) (map[string]interface{}, error) {

	method := "POST"
	content := make(map[string]interface{})
	postdata, err := json.Marshal(parMap)
	if err != nil {
		return content, err
	}
	got := string(postdata)
	payload := strings.NewReader(got)

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Println(err)
		return content, err
	}
	req.Header.Add("Token", token)
	req.Header.Add("Content-Type", "application/json")
	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return content, err
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return content, err
	}
	json.Unmarshal(body, &content)
	return content, err
}

// ServiceClient ***
type ServiceClient struct {
	request *req.Req
}

// the v ...interface{} params can be
// Headers : cqe.Header, utils.Header
// Params  : cqe.Param, cqe.QueryParam, url.Values
// Body    : *cqe.bodyJson, *cqe.bodyXml, string, []byte, bytes.Buffer
// Files   : cqe.FileUpload, []FileUpload
// Cookie  : utils.Cookie
// Callback: cqe.UploadProgress, cqe.DownloadProgress

// Get ***
func (o *ServiceClient) Get(url string, v ...interface{}) *req.Resp {
	resp, err := o.request.Get(url, v...)
	if err == nil {
		return resp
	}
	return nil
}

// Post ***
func (o *ServiceClient) Post(url string, v ...interface{}) *req.Resp {
	resp, err := o.request.Post(url, v...)
	if err == nil {
		return resp
	}
	return nil
}

// Put ***
func (o *ServiceClient) Put(url string, v ...interface{}) *req.Resp {
	resp, err := o.request.Put(url, v...)
	if err == nil {
		return resp
	}
	return nil
}

// Delete ***
func (o *ServiceClient) Delete(url string, v ...interface{}) *req.Resp {
	resp, err := o.request.Delete(url, v...)
	if err == nil {
		return resp
	}
	return nil
}

// Head ***
func (o *ServiceClient) Head(url string, v ...interface{}) *req.Resp {
	resp, err := o.request.Head(url, v...)
	if err == nil {
		return resp
	}
	return nil
}
